#include "../include/utils.h"

bool replace(std::string& str, const std::string& from, const std::string& to) {
    size_t start_pos = str.find(from);
    if(start_pos == std::string::npos)
        return false;
    str.replace(start_pos, from.length(), to);
    return true;
}

string lower(string &str) {
    string lowerStr;
    for (int i=0; i < str.length()-1; i++) {
        lowerStr += tolower(str[i]);
    }
    return lowerStr;
}

string cropLine(string &line, int limit) {
    if (line.length() > limit) {
        return line.substr(0, limit-3) + "...";
    }
    return line; 
}

void split(string &str, char delim, vector<string> &out) {
    size_t start;
    size_t end = 0;

    while ((start = str.find_first_not_of(delim, end)) != string::npos)
    {
        end = str.find(delim, start);
        out.push_back(str.substr(start, end - start));
    }
}

void splitCommand(string &command, vector<string> &out) {
	size_t space_pos = command.find(" ");

	if (space_pos != string::npos) {
		out.push_back(command.substr(0, space_pos));
		out.push_back(command.substr(space_pos + 1));
	}
}

bool isStringHasSpace(string &str) {
	size_t space_pos = str.find(" ");
	return space_pos != string::npos;
}

pid_t CreateProcess(const char* command, const char* parametersIn) {
    const int maxNumArgs = 1024;
    const char* args[maxNumArgs];
    char* parameters = NULL;

	freopen("/dev/null", "r", stdin);
	freopen("/dev/null", "w", stdout);
	freopen("/dev/null", "w", stderr);

    memset(args, 0, (sizeof(char*) * maxNumArgs));
    args[0] = command;

    if(parametersIn != NULL) {
        parameters = strdup(parametersIn);
        int strLen = strlen(parameters);

        int numParameters = 1;
        bool expectNextParam = true;
        int i;
        for(i = 0; i < strLen; i++) {
            if(parameters[i] == ' ' || parameters[i] == '\t' ||
               parameters[i] == '\n')
            {
                expectNextParam = true;
                parameters[i] = '\0';
            } else if(expectNextParam) {
                args[numParameters] = &(parameters[i]);
                numParameters++;
                expectNextParam = false;
            }
        }
    }

    pid_t pid = fork();
    if (pid == 0) {
		setsid();

		extern char **environ;

		if (command[0] == '/') 
			execve(command, (char**)args, environ);
		else
			execvpe(command, (char**)args, environ);
        _exit(1);
    }

    if(parameters != NULL)
        free(parameters);

	//waitpid(pid, NULL, 0);

    return pid;
}

